<script setup>
    import {
        Edit,
        Delete,
        BellFilled,
        Search
    } from '@element-plus/icons-vue'
    import axios from 'axios';
    import {onMounted, ref} from 'vue'
    // 导入 ExcelJS 库
    import ExcelJS from 'exceljs/dist/exceljs.min.js';
    //声明一个异步的函数
    import {
        MainClassListBySearchTeacherService
    } from '@/api/mainClass.js'
    import {
        TeacherListAllSerivce
    } from '@/api/teacher.js'
    import {
        ProfessionListAllSerivce
    } from '@/api/profession.js'
    import {
        ElMessage,
    } from 'element-plus'
    const mainClasss = ref([{
        "classId":1,
        "className":"",
        "classNumber":"",
        "teacherId":"",
        "professionId":""
    }])

    const teachers = ref([{
        "teacherId":1,
        "teacherName":"",
        "teacherPhone":"",
        "teacherPhoto":"",
        "professionId":""
    }])

    const professions = ref([{
        "professionId":1,
        "professionName":"",
        "professionType":""
    }])

    
    const teacherAll = async () => {
        try {
            const result = await TeacherListAllSerivce();
            teachers.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }

    const professionAll = async () => {
        try {
            const result = await ProfessionListAllSerivce();
            professions.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }
    
    const jwtToken = localStorage.getItem('teacherJwtToken');
    // 设置请求头部，包含jwt令牌
    const config = {
        headers: {
            Authorization: `Bearer ${jwtToken}`
        }
    };
    const teacherModel = ref({
        teacherId: '',
        teacherName: '',
        teacherPassword: '',
        teacherPhoto: '',
        teacherPhone:'',
        professionId:1,
        professionName:''
    });
    const fetchData = async () => {
        try {
            const response = await axios.get('http://localhost:9090/teacher/jwt', config);
            const teacherData = response.data.data.teacher;
            if (teacherData) {
                teacherModel.value.teacherId = teacherData.teacherId;
                teacherModel.value.teacherName = teacherData.teacherName;
                teacherModel.value.teacherPassword = teacherData.teacherPassword;
                teacherModel.value.teacherPhone=teacherData.teacherPhone
                teacherModel.value.teacherPhoto = teacherData.teacherPhoto;
                teacherModel.value.professionId=teacherData.professionId;
                professionAll();
                // 获取对应的专业名称并添加到教师对象中
                    const profession = professions.value.find(prof => prof.professionId === teacherModel.value.professionId);
                    if (profession) {
                        teacherModel.value.professionName = profession.professionName;
                    }
                    teacherAll();
                    search();
            } else {
                console.error('User data not found in the response');
            }
        } catch (error) {
            console.log(error);
        }
    };
    //分页
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(20)
    const handleSizeChange = (val) => {
        pageSize.value = val;
        search();
    }
    const handleCurrentChange = (val) => {
        currentPage.value = val;
        search();
    }
    onMounted(() => {
        fetchData();
    });

  
    const multipleSelection = ref([])
 
    
    const handleSelectionChange = (val) => {
        multipleSelection.value = val
    }
    // 导出
    const exportSelected = () => {
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: 'error',
                message: '请选择要导出的数据',
            });
            return;
        }

        // 创建一个新的工作簿
        const workbook = new ExcelJS.Workbook();

        // 添加一个工作表
        const worksheet = workbook.addWorksheet('Sheet1');

        // 设置表头信息
        worksheet.addRow(['班级名称','包含人数','老师编号']);

        // 获取选择的数据
        const selectedData = multipleSelection.value;

        // 将数据添加到工作表中
        selectedData.forEach(row => {
            worksheet.addRow([
                row.className,
                row.classNumber,
                row.teacherId,
            ]);
        });

        // 将工作簿保存为Excel文件
        workbook.xlsx.writeBuffer()
            .then(buffer => {
                const blob = new Blob([buffer], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                });
                const fileName = '班级数据.xlsx';

                // 创建下载链接并触发下载
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                link.click();

                ElMessage({
                    type: 'success',
                    message: '导出成功',
                });
            })
            .catch(error => {
                console.error('导出Excel文件时出错:', error);
                ElMessage({
                    type: 'error',
                    message: '导出失败',
                });
            });
    }
      //搜索
    const input = ref("");
    const select = ref("1");
    const search = async () => {
        try {
            console.log(teacherModel.value.teacherId)
            const result = await MainClassListBySearchTeacherService(input.value, teacherModel.value.teacherId, select.value, currentPage.value, pageSize.value);
            console.log(result)
            mainClasss.value = result.data.rows;
            total.value = result.data.total;
            // 遍历班级数据，获取对应的教师名称并添加到班级对象中
            mainClasss.value.forEach(mainClass => {
                const teacher = teachers.value.find(teac => teac.teacherId === mainClass.teacherId);
                if (teacher) {
                mainClass.teacherName = teacher.teacherName;
                }
            });
            // 遍历专业数据，获取对应的专业名称并添加到班级对象中
            mainClasss.value.forEach(mainClass => {
                const profession = professions.value.find(prof => prof.professionId === mainClass.professionId);
                if (profession) {
                    mainClass.professionName = profession.professionName;
                }
            });
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }

</script>
<template>
    
    <div class="card-container">
        <el-card class="page-container">
            <template #header>
                <div class="header">
                    <span style="font-size: 14px;"><b>班级管理</b></span>
                    <div class="extra">
                        <el-input v-model="input" placeholder="请输入" class="input-with-select">
                            <template #prepend>
                                <el-select v-model="select" placeholder="班级名称" style="width: 115px">
                                    <el-option label="班级名称" value="1" />
                                </el-select>
                            </template>
                            <template #append>
                                <el-button :icon="Search" @click="search(input,select,currentPage,pageSize)" />
                            </template>
                        </el-input>
                        <el-button type="success" @click="exportSelected()" plain>导出</el-button>
                    </div>
                </div>
            </template>
            <el-table :data="mainClasss" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="200" type="index" align="center"> </el-table-column>
                <el-table-column label="班级名称" width="300" prop="className" align="center"></el-table-column>
                <el-table-column label="学生人数" width="300" prop="classNumber" align="center"></el-table-column>
                <el-table-column label="授课老师" width="300" prop="teacherName" align="center"></el-table-column>
                <!-- <el-table-column label="操作" width="150">
                    <template #default="{ row }">
                        <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                        <el-button :icon="Delete" circle plain type="danger" @click="deletemainClass(row)"></el-button>
                    </template>
                </el-table-column> -->
                <template #empty>
                    <el-empty description="没有数据" />
                </template>
            </el-table>

        </el-card>
    </div>
    <el-pagination class="el-p" v-model:current-page="currentPage" v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]" :background="true" layout="jumper,total, sizes, prev, pager, next " :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<style lang="scss" scoped>
    .card-container {
        height: 520px;
        /* 设置合适的固定高度 */
        overflow: auto;
    }

    .page-container {
        min-height: 100%;
        box-sizing: border-box;

        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .extra {
                display: flex;
                align-items: center;

                .el-input {
                    margin-right: 400px;
                }
            }
        }
    }

    .custom-date-picker {
        display: flex;
        width: 100%;
        padding: 0;
        flex-wrap: wrap;
    }

    .el-p {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
    }

    .input-with-select {
        background-color: var(--el-fill-color-blank);
    }
    // 调整样式
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}

</style>